﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Furion.DataEncryption.Extensions;
using Furion.Logging;
using Furion.SpecificationDocument;
using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PMP.Core.Entities;
using PMP.Core.Enums;
using PMP.Core.SqlSugar;
using SqlSugar;

namespace PMP.Web.Core;

public static class StartupEx
{
    
    public static void MyConfigure(this IApplicationBuilder app)
    {
        app.ConfigWwwroot();
        app.ConfigSwagger();
 
    }
    /// <summary>
    /// 服务注册
    /// </summary>
    /// <param name="services"></param>
    public static void RegisterServices(this IServiceCollection services)
    {
        services.RegisterLog();
        InitializeDatabase();
        
    }
    
    
    private static void ConfigWwwroot(this IApplicationBuilder app)
    {
        DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
        defaultFilesOptions.DefaultFileNames.Clear();
        //设置首页，打开`localhost`访问到的是`wwwroot`下的Index.html文件
        defaultFilesOptions.DefaultFileNames.Add("index.html");
        app.UseDefaultFiles(defaultFilesOptions);
        app.UseStaticFiles();
    }
    private static void ConfigSwagger(this IApplicationBuilder app)
    {
        app.UseKnife4UI(options =>
        {
            options.RoutePrefix = "kapi"; // 配置 Knife4UI 路由地址，现在是 /newapi
            foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
            {
                options.SwaggerEndpoint("/" + groupInfo.RouteTemplate, groupInfo.Title);
            }
        });
        app.UseInject(string.Empty,
            options => { options.ConfigureSwaggerUI(uiOptions => { uiOptions.RoutePrefix = "api"; }); });
    }
    
    
    /// <summary>
    /// 注册文件日志服务
    /// </summary>
    /// <param name="services"></param>
    public static void RegisterLog(this IServiceCollection services)
    {
        // 循环枚举 LogLevel
        foreach (LogLevel logLevel in Enum.GetValues(typeof(LogLevel)))
        {
            var fileName = $"1_log/{logLevel}_{DateTime.Today:yyyyMMdd}.log";
            var filePath = Path.Combine(AppContext.BaseDirectory, fileName);
            services.AddFileLogging(filePath, options =>
            {
                options.WriteFilter = (logMsg) =>
                {
                    return logMsg.LogLevel == logLevel;
                };
            });
        }

    }
    
        /// <summary>
    /// 初始化数据库
    /// </summary>
    private static void InitializeDatabase()
    {
        try
        {
            DbContext.Instance.DbMaintenance.CreateDatabase();
            List<Type> types = typeof(BaseEntity).Assembly.GetTypes()
                // .Where(it => it.GetCustomAttributes(typeof(SugarTable), false).Length > 0)
                .Where(a=>a.FullName?.Contains("PMP.Core.Entities") == true)
                .Where(a => a.Name != nameof(BaseEntity))
                .ToList();
            DbContext.Instance.CodeFirst.SetStringDefaultLength(200).InitTables(types.ToArray());

            // 初始化离线用户
            var userCount = DbContext.Instance.Queryable<TbAccount>().Count();
            var offlineUsers = new List<TbAccount>()
            {
                new () { Id = 1,UserName = "admin",RealName = "张三", Password = "12345".ToMD5Encrypt(), UserLevel = EnumUserLevel.Level2 ,IsSuperAdmin = true},
                new () { Id = 2,UserName = "testuser001",RealName = "李一", Password = "12345".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level1,ReferrerUserId = 1},
                new () { Id = 3,UserName = "testuser002",RealName = "李二", Password = "12345".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level1,ReferrerUserId = 1},
                new () { Id = 4,UserName = "testuser011",RealName = "王一", Password = "12345".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level0,ReferrerUserId = 2},
                new () { Id = 5,UserName = "testuser012",RealName = "王二", Password = "12345".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level0,ReferrerUserId = 2},
                new () { Id = 6,UserName = "testuser013",RealName = "赵一", Password = "12345".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level0,ReferrerUserId = 3},
                new () { Id = 7,UserName = "testuser014",RealName = "赵二", Password = "12345".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level0,ReferrerUserId = 3},
                new () { Id = 7,UserName = "testuser014",RealName = "赵二", Password = "12345".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level0,ReferrerUserId = 3},
                
                // new () { Id = 1,UserName = "xiazong",RealName = "夏总", Password = "123456".ToMD5Encrypt(), UserLevel = EnumUserLevel.Level2 ,IsSuperAdmin = true},
                // new () { Id = 2,UserName = "dongzong",RealName = "董总", Password = "123456".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level2,ReferrerUserId = 0},
                // new () { Id = 3,UserName = "gouzong",RealName = "苟总", Password = "123456".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level2,ReferrerUserId = 0},
                // new () { Id = 4,UserName = "qinzong",RealName = "秦总", Password = "123456".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level2,ReferrerUserId = 0},
                // new () { Id = 5,UserName = "zhengzong",RealName = "郑总", Password = "123456".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level2,ReferrerUserId = 0},
                // new () { Id = 6,UserName = "wangzong",RealName = "汪总", Password = "123456".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level2,ReferrerUserId = 0},
                // new () { Id = 7,UserName = "zhangzong",RealName = "张总", Password = "123456".ToMD5Encrypt() , UserLevel = EnumUserLevel.Level2,ReferrerUserId = 0},
                };
            if(userCount == 0)
            {
                DbContext.Instance.Insertable(offlineUsers).ExecuteCommand();
            }
            
            // 初始化标签表
            var tagCount = DbContext.Instance.Queryable<TbTag>().Count();
            var tags = new List<TbTag>()
            {
                // 人员-身份
                new TbTag() { TagType = 0, Category = "身份", TagName = "超级管理员", SortNum = 1 },
                new TbTag() { TagType = 0, Category = "身份", TagName = "管理员", SortNum = 2 },
                new TbTag() { TagType = 0, Category = "身份", TagName = "管理合伙人", SortNum = 3 },
                new TbTag() { TagType = 0, Category = "身份", TagName = "高级合伙人", SortNum = 4 },
                new TbTag() { TagType = 0, Category = "身份", TagName = "合伙人", SortNum = 5 },
                // 人员-部门
                new TbTag() { TagType = 0, Category = "部门", TagName = "综合部", SortNum = 1 },
                new TbTag() { TagType = 0, Category = "部门", TagName = "市场部", SortNum = 2 },
                new TbTag() { TagType = 0, Category = "部门", TagName = "投融资部", SortNum = 3 },
                new TbTag() { TagType = 0, Category = "部门", TagName = "孵化部", SortNum = 4 },
                new TbTag() { TagType = 0, Category = "部门", TagName = "产品部", SortNum = 5 },
                new TbTag() { TagType = 0, Category = "部门", TagName = "营销部", SortNum = 6 },
                // 人员-行业
                new TbTag() { TagType = 0, Category = "行业", TagName = "软件系统", SortNum = 1 },
                new TbTag() { TagType = 0, Category = "行业", TagName = "机器人与装备", SortNum = 2 },
                new TbTag() { TagType = 0, Category = "行业", TagName = "脑机接口", SortNum = 3 },
                new TbTag() { TagType = 0, Category = "行业", TagName = "生命健康", SortNum = 4 },
                new TbTag() { TagType = 0, Category = "行业", TagName = "半导体", SortNum = 5 },
                new TbTag() { TagType = 0, Category = "行业", TagName = "化工与新材料新能源", SortNum = 6 },
                // 人员-地域
                new TbTag() { TagType = 0, Category = "地域", TagName = "籍贯地", SortNum = 1 },
                new TbTag() { TagType = 0, Category = "地域", TagName = "工作所在地", SortNum = 2 },
                // 项目-项目等级
                new TbTag() { TagType = 1, Category = "项目等级", TagName = "重点项目", SortNum = 1 },
                new TbTag() { TagType = 1, Category = "项目等级", TagName = "高伙项目", SortNum = 2 },
                new TbTag() { TagType = 1, Category = "项目等级", TagName = "储备项目", SortNum = 3 },
                // 项目-需求
                new TbTag() { TagType = 1, Category = "需求", TagName = "市场拓展", SortNum = 1 },
                new TbTag() { TagType = 1, Category = "需求", TagName = "投融资", SortNum = 2 },
                new TbTag() { TagType = 1, Category = "需求", TagName = "孵化", SortNum = 3 },
                new TbTag() { TagType = 1, Category = "需求", TagName = "团队搭建", SortNum = 4 },
                new TbTag() { TagType = 1, Category = "需求", TagName = "人才项目", SortNum = 5 },
                new TbTag() { TagType = 1, Category = "需求", TagName = "产业化落地", SortNum = 6 },
                // 项目-行业
                new TbTag() { TagType = 1, Category = "行业", TagName = "软件系统", SortNum = 1 },
                new TbTag() { TagType = 1, Category = "行业", TagName = "机器人与装备", SortNum = 2 },
                new TbTag() { TagType = 1, Category = "行业", TagName = "脑机接口", SortNum = 3 },
                new TbTag() { TagType = 1, Category = "行业", TagName = "生命健康", SortNum = 4 },
                new TbTag() { TagType = 1, Category = "行业", TagName = "半导体", SortNum = 5 },
                new TbTag() { TagType = 1, Category = "行业", TagName = "化工与新材料新能源", SortNum = 6 },
                // 项目-地域
                new TbTag() { TagType = 1, Category = "地域", TagName = "全国各省市", SortNum = 1 },
                // 项目-项目阶段
                new TbTag() { TagType = 1, Category = "项目阶段", TagName = "未成立公司", SortNum = 1 },
                new TbTag() { TagType = 1, Category = "项目阶段", TagName = "种子轮", SortNum = 2 },
                new TbTag() { TagType = 1, Category = "项目阶段", TagName = "天使轮", SortNum = 3 },
                new TbTag() { TagType = 1, Category = "项目阶段", TagName = "A轮", SortNum = 4 },
                new TbTag() { TagType = 1, Category = "项目阶段", TagName = "B轮", SortNum = 5 },
                new TbTag() { TagType = 1, Category = "项目阶段", TagName = "C轮后", SortNum = 6 }

            };
            if (tagCount != tags.Count)
            {
                DbContext.Instance.Deleteable<TbTag>().ExecuteCommand();
                DbContext.Instance.Insertable(tags).ExecuteCommand();
            }

        }
        catch (Exception e)
        {
            Log.Error("", e);
        }
    }
    
}